

module Schnell
  class Link < Element
    ELEMENT_TYPE = "a"
    
    # used internally to locate the link
    def locate
        if @how ==  :text
          links = @page.getByXPath("//#{self.class::ELEMENT_TYPE}")
          selected_links = links.collect{|link| link.asText == @what}
          index = selected_links.index(true)
          @element = links[index] if not index.nil?
        elsif @how == :url or @how == :href
          @element = @page.getByXPath("//#{self.class::ELEMENT_TYPE}[@href='#{@what}']")[0]
        else
          super()
      end
    end
    
    private :locate
        
    # returns true if link has an image embedded in it
    def has_image?
      assert_exists
      return true if @element.getFirstChild.is_a?(Java::ComGargoylesoftwareHtmlunitHtml::HtmlImage)
      return false
    end    
    
    # return the src of the element
    def src
      assert_exists
      if @element.getElementsByTagName("IMG").length > 0
        return @element.getElementsByTagName("IMG")[0].getAttribute("src")
      else
        return ""
      end
    end
    
    # return the text of the element
    def innerText
      assert_exists
      return @element.asText      
    end
    
    alias text innerText
    
    # return the href of the link
    def_wrap_guard :href
    # return the class name of the link
    def_wrap :class_name, :class
    # retun the type of the link
    def_wrap_guard :type
  end
end
